import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
Vue.use(Router)

Router.prototype.closeto = function (data) {
  this.replace({
    path: data.path,
    query: data.query
  })
}

Router.prototype.goto = function (data) {
  this.push({
    path: data.path,
    query: data.query
  })
}

Router.prototype.back = function (n) {
  this.go(n || -1)
}

//const footer = () => import('@/components/footer/')
const RouterModel = new Router({
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  },
  routes: [
    {
      path: '/',
      name: 'index',
      components: {
        default: r => require(['@/views/index.vue'], r)
      },
      meta: {
        keepAlive: true,
        title: ''
      }
    },
    {
      path: '/articleList',
      name: 'articleList',
      components: {
        default: r => require(['@/views/articleList.vue'], r)
      },
      meta: {
        keepAlive: true,
        title: ''
      }
    },
    {
      path: '/articleDetail',
      name: 'articleDetail',
      components: {
        default: r => require(['@/views/articleDetail.vue'], r)
      },
      meta: {
        title: ''
      }
    },
    {
      path: '/contactUs',
      name: 'contactUs',
      components: {
        default: r => require(['@/views/contactUs.vue'], r)
      },
      meta: {
        title: ''
      }
    },
    {
      path: '/options',
      name: 'options',
      components: {
        default: r => require(['@/views/options.vue'], r)
      },
      meta: {
        title: ''
      }
    },
    {
      path: '*',
      redirect: '/'
    }
  ]
})

RouterModel.beforeEach(async (to, from, next) => {
  const hasHomeInfo = store.getters.homeInfo && store.getters.commonSys.length > 0
  if (hasHomeInfo) {
    next()
  } else {
    try {
      await store.dispatch('common/getInfo')
      next()
    } catch (error) {
      console.log(error)
    }
  }
})

// function handleNext(to, from, next) {
//   if (needLogin == 1) {
//     let id = COMMON.getStorage('id')
//     let pctoken = COMMON.getStorage('pctoken')
//     let has = !!(id && id !== 'undefined' && pctoken && pctoken !== 'undefined')
//     if (has) {
//       if (to.path !== '/login') {
//         next()
//       } else {
//         next('/')
//       }
//     } else {
//       if (to.matched.some(record => record.meta.require)) {
//         if (to.path !== '/login') {
//           COMMON.setStorage('fullPath', to.fullPath)
//           next({
//             path: '/login',
//             query: to.query
//           })
//         } else {
//           next()
//         }
//       } else {
//         next()
//       }
//     }
//   }
//   if (needLogin == 0) {
//     if (to.path !== '/login') {
//       next()
//     } else {
//       next('/')
//     }
//   }
// }

export default RouterModel
